//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package org_forum_api_serv

import (
	"context"
	"time"

	"atomgit.com/openlinksaas/api-server/dao"
	"atomgit.com/openlinksaas/api-server/dao/org_dao"
	"atomgit.com/openlinksaas/api-server/dao/user_dao"
	"atomgit.com/openlinksaas/proto-gen-go.git/org_forum_api"
	"github.com/google/uuid"
	"go.mongodb.org/mongo-driver/mongo"
)

func (apiImpl *OrgForumApiImpl) CreateThread(ctx context.Context, req *org_forum_api.CreateThreadRequest) (*org_forum_api.CreateThreadResponse, error) {
	sessionItem, ok := dao.CacheDao.GetSession(ctx, req.SessionId)
	if !ok {
		return &org_forum_api.CreateThreadResponse{
			Code:   org_forum_api.CreateThreadResponse_CODE_WRONG_SESSION,
			ErrMsg: "会话不存在",
		}, nil
	}
	exist, err := org_dao.OrgInfoDao.Exist(ctx, req.OrgId)
	if err != nil {
		return nil, err
	}
	if !exist {
		return &org_forum_api.CreateThreadResponse{
			Code:   org_forum_api.CreateThreadResponse_CODE_NO_ORG,
			ErrMsg: "组织不存在",
		}, nil
	}
	exist, err = org_dao.MemberDao.Exist(ctx, req.OrgId, sessionItem.UserId)
	if err != nil {
		return nil, err
	}
	if !exist {
		return &org_forum_api.CreateThreadResponse{
			Code:   org_forum_api.CreateThreadResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	}
	forumItem, err := org_dao.ForumDao.Get(ctx, req.OrgId, req.ForumId)
	if err != nil {
		return &org_forum_api.CreateThreadResponse{
			Code:   org_forum_api.CreateThreadResponse_CODE_NO_FORUM,
			ErrMsg: "讨论组不存在",
		}, nil
	}
	forum := forumItem.ToOrgForumInfo(sessionItem.UserId)
	if !forum.UserPerm.CreateThread {
		return &org_forum_api.CreateThreadResponse{
			Code:   org_forum_api.CreateThreadResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	}

	threadId := uuid.NewString()
	contentId := uuid.NewString()
	nowTime := time.Now().UnixNano() / 1e6

	dbSess, err := dao.StartSession()
	if err != nil {
		return nil, err
	}
	defer dao.EndSession(dbSess)

	ret, err := dbSess.WithTransaction(ctx, func(sessCtx mongo.SessionContext) (interface{}, error) {
		err = org_dao.ThreadContentDao.Insert(sessCtx, &org_dao.ThreadContentInfoDbItem{
			ContentId:  contentId,
			OrgId:      req.OrgId,
			ForumId:    req.ForumId,
			ThreadId:   threadId,
			Content:    req.Content,
			UserId:     sessionItem.UserId,
			CreateTime: nowTime,
			UpdateTime: nowTime,
		})
		if err != nil {
			return nil, err
		}
		err = org_dao.ForumThreadDao.Insert(sessCtx, &org_dao.ForumThreadInfoDbItem{
			ThreadId:       threadId,
			OrgId:          req.OrgId,
			ForumId:        req.ForumId,
			Title:          req.Title,
			Weight:         0,
			FirstContentId: contentId,
			UserId:         sessionItem.UserId,
			CreateTime:     nowTime,
			UpdateTime:     nowTime,
			ContentCount:   1,
		})
		if err != nil {
			return nil, err
		}
		//更新论坛会话数量
		count, err := org_dao.ForumThreadDao.Count(sessCtx, req.OrgId, req.ForumId)
		if err != nil {
			return nil, err
		}
		err = org_dao.ForumDao.UpdateThreadCount(sessCtx, req.OrgId, req.ForumId, count)
		if err != nil {
			return nil, err
		}
		return &org_forum_api.CreateThreadResponse{
			Code:      org_forum_api.CreateThreadResponse_CODE_OK,
			ThreadId:  threadId,
			ContentId: contentId,
		}, nil
	})
	if err != nil {
		return nil, err
	}
	return ret.(*org_forum_api.CreateThreadResponse), nil
}

func (apiImpl *OrgForumApiImpl) UpdateThread(ctx context.Context, req *org_forum_api.UpdateThreadRequest) (*org_forum_api.UpdateThreadResponse, error) {
	sessionItem, ok := dao.CacheDao.GetSession(ctx, req.SessionId)
	if !ok {
		return &org_forum_api.UpdateThreadResponse{
			Code:   org_forum_api.UpdateThreadResponse_CODE_WRONG_SESSION,
			ErrMsg: "会话不存在",
		}, nil
	}
	exist, err := org_dao.OrgInfoDao.Exist(ctx, req.OrgId)
	if err != nil {
		return nil, err
	}
	if !exist {
		return &org_forum_api.UpdateThreadResponse{
			Code:   org_forum_api.UpdateThreadResponse_CODE_NO_ORG,
			ErrMsg: "组织不存在",
		}, nil
	}
	exist, err = org_dao.MemberDao.Exist(ctx, req.OrgId, sessionItem.UserId)
	if err != nil {
		return nil, err
	}
	if !exist {
		return &org_forum_api.UpdateThreadResponse{
			Code:   org_forum_api.UpdateThreadResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	}
	exist, err = org_dao.ForumDao.Exist(ctx, req.OrgId, req.ForumId)
	if err != nil {
		return nil, err
	}
	if !exist {
		return &org_forum_api.UpdateThreadResponse{
			Code:   org_forum_api.UpdateThreadResponse_CODE_NO_FORUM,
			ErrMsg: "讨论组不存在",
		}, nil
	}
	threadItem, err := org_dao.ForumThreadDao.Get(ctx, req.OrgId, req.ForumId, req.ThreadId)
	if err != nil {
		return &org_forum_api.UpdateThreadResponse{
			Code:   org_forum_api.UpdateThreadResponse_CODE_NO_THREAD,
			ErrMsg: "讨论会话不存在",
		}, nil
	}
	if threadItem.UserId != sessionItem.UserId {
		return &org_forum_api.UpdateThreadResponse{
			Code:   org_forum_api.UpdateThreadResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	}

	nowTime := time.Now().UnixNano() / 1e6

	dbSess, err := dao.StartSession()
	if err != nil {
		return nil, err
	}
	defer dao.EndSession(dbSess)

	ret, err := dbSess.WithTransaction(ctx, func(sessCtx mongo.SessionContext) (interface{}, error) {
		err = org_dao.ForumThreadDao.Update(sessCtx, req.OrgId, req.ForumId, req.ThreadId, req.Title, nowTime)
		if err != nil {
			return nil, err
		}
		return &org_forum_api.UpdateThreadResponse{
			Code: org_forum_api.UpdateThreadResponse_CODE_OK,
		}, nil
	})
	if err != nil {
		return nil, err
	}
	return ret.(*org_forum_api.UpdateThreadResponse), nil
}

func (apiImpl *OrgForumApiImpl) SetThreadWeight(ctx context.Context, req *org_forum_api.SetThreadWeightRequest) (*org_forum_api.SetThreadWeightResponse, error) {
	sessionItem, ok := dao.CacheDao.GetSession(ctx, req.SessionId)
	if !ok {
		return &org_forum_api.SetThreadWeightResponse{
			Code:   org_forum_api.SetThreadWeightResponse_CODE_WRONG_SESSION,
			ErrMsg: "会话不存在",
		}, nil
	}
	orgItem, err := org_dao.OrgInfoDao.Get(ctx, req.OrgId)
	if err != nil {
		return &org_forum_api.SetThreadWeightResponse{
			Code:   org_forum_api.SetThreadWeightResponse_CODE_NO_ORG,
			ErrMsg: "组织不存在",
		}, nil
	}

	if orgItem.OwnerUserId != sessionItem.UserId {
		return &org_forum_api.SetThreadWeightResponse{
			Code:   org_forum_api.SetThreadWeightResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	}
	exist, err := org_dao.ForumDao.Exist(ctx, req.OrgId, req.ForumId)
	if err != nil {
		return nil, err
	}
	if !exist {
		return &org_forum_api.SetThreadWeightResponse{
			Code:   org_forum_api.SetThreadWeightResponse_CODE_NO_FORUM,
			ErrMsg: "讨论组不存在",
		}, nil
	}
	exist, err = org_dao.ForumThreadDao.Exist(ctx, req.OrgId, req.ForumId, req.ThreadId)
	if err != nil {
		return nil, err
	}
	if !exist {
		return &org_forum_api.SetThreadWeightResponse{
			Code:   org_forum_api.SetThreadWeightResponse_CODE_NO_THREAD,
			ErrMsg: "讨论会话不存在",
		}, nil
	}
	dbSess, err := dao.StartSession()
	if err != nil {
		return nil, err
	}
	defer dao.EndSession(dbSess)

	ret, err := dbSess.WithTransaction(ctx, func(sessCtx mongo.SessionContext) (interface{}, error) {
		err = org_dao.ForumThreadDao.UpdateWeight(sessCtx, req.OrgId, req.ForumId, req.ThreadId, req.Weight)
		if err != nil {
			return nil, err
		}
		return &org_forum_api.SetThreadWeightResponse{
			Code: org_forum_api.SetThreadWeightResponse_CODE_OK,
		}, nil
	})
	if err != nil {
		return nil, err
	}
	return ret.(*org_forum_api.SetThreadWeightResponse), nil
}

func (apiImpl *OrgForumApiImpl) ListThread(ctx context.Context, req *org_forum_api.ListThreadRequest) (*org_forum_api.ListThreadResponse, error) {
	emptyList := []*org_forum_api.ForumThreadInfo{}

	sessionItem, ok := dao.CacheDao.GetSession(ctx, req.SessionId)
	if !ok {
		return &org_forum_api.ListThreadResponse{
			Code:       org_forum_api.ListThreadResponse_CODE_WRONG_SESSION,
			ErrMsg:     "会话不存在",
			ThreadList: emptyList,
		}, nil
	}
	exist, err := org_dao.OrgInfoDao.Exist(ctx, req.OrgId)
	if err != nil {
		return nil, err
	}
	if !exist {
		return &org_forum_api.ListThreadResponse{
			Code:       org_forum_api.ListThreadResponse_CODE_NO_ORG,
			ErrMsg:     "组织不存在",
			ThreadList: emptyList,
		}, nil
	}
	exist, err = org_dao.MemberDao.Exist(ctx, req.OrgId, sessionItem.UserId)
	if err != nil {
		return nil, err
	}
	if !exist {
		return &org_forum_api.ListThreadResponse{
			Code:       org_forum_api.ListThreadResponse_CODE_NO_PERMISSION,
			ErrMsg:     "没有权限",
			ThreadList: emptyList,
		}, nil
	}
	forumItem, err := org_dao.ForumDao.Get(ctx, req.OrgId, req.ForumId)
	if err != nil {
		return &org_forum_api.ListThreadResponse{
			Code:       org_forum_api.ListThreadResponse_CODE_NO_FORUM,
			ErrMsg:     "讨论组不存在",
			ThreadList: emptyList,
		}, nil
	}

	threadItemList, err := org_dao.ForumThreadDao.List(ctx, req.OrgId, req.ForumId, int64(req.Offset), int64(req.Limit))
	if err != nil {
		return nil, err
	}
	//获取用户信息
	userIdList := []string{}
	for _, threadItem := range threadItemList {
		userIdList = append(userIdList, threadItem.UserId)
	}
	userItemList, err := user_dao.UserInfoDao.ListById(ctx, userIdList)
	if err != nil {
		return nil, err
	}
	userItemMap := map[string]*user_dao.UserInfoDbItem{}
	for _, userItem := range userItemList {
		userItemMap[userItem.UserId] = userItem
	}

	//生产结果
	threadList := []*org_forum_api.ForumThreadInfo{}
	for _, threadItem := range threadItemList {
		thread := threadItem.ToForumThreadInfo()
		userItem, ok := userItemMap[threadItem.UserId]
		if ok {
			thread.UserDisplayName = userItem.BasicInfo.DisplayName
			thread.UserLogoUri = userItem.BasicInfo.LogoUri
		}
		threadList = append(threadList, thread)
	}
	return &org_forum_api.ListThreadResponse{
		Code:       org_forum_api.ListThreadResponse_CODE_OK,
		TotalCount: forumItem.ThreadCount,
		ThreadList: threadList,
	}, nil
}

func (apiImpl *OrgForumApiImpl) GetThread(ctx context.Context, req *org_forum_api.GetThreadRequest) (*org_forum_api.GetThreadResponse, error) {
	emptyInfo := &org_forum_api.ForumThreadInfo{}

	sessionItem, ok := dao.CacheDao.GetSession(ctx, req.SessionId)
	if !ok {
		return &org_forum_api.GetThreadResponse{
			Code:       org_forum_api.GetThreadResponse_CODE_WRONG_SESSION,
			ErrMsg:     "会话不存在",
			ThreadInfo: emptyInfo,
		}, nil
	}
	exist, err := org_dao.OrgInfoDao.Exist(ctx, req.OrgId)
	if err != nil {
		return nil, err
	}
	if !exist {
		return &org_forum_api.GetThreadResponse{
			Code:       org_forum_api.GetThreadResponse_CODE_NO_ORG,
			ErrMsg:     "组织不存在",
			ThreadInfo: emptyInfo,
		}, nil
	}
	exist, err = org_dao.MemberDao.Exist(ctx, req.OrgId, sessionItem.UserId)
	if err != nil {
		return nil, err
	}
	if !exist {
		return &org_forum_api.GetThreadResponse{
			Code:       org_forum_api.GetThreadResponse_CODE_NO_PERMISSION,
			ErrMsg:     "没有权限",
			ThreadInfo: emptyInfo,
		}, nil
	}
	exist, err = org_dao.ForumDao.Exist(ctx, req.OrgId, req.ForumId)
	if err != nil {
		return nil, err
	}
	if !exist {
		return &org_forum_api.GetThreadResponse{
			Code:       org_forum_api.GetThreadResponse_CODE_NO_FORUM,
			ErrMsg:     "讨论组不存在",
			ThreadInfo: emptyInfo,
		}, nil
	}
	threadItem, err := org_dao.ForumThreadDao.Get(ctx, req.OrgId, req.ForumId, req.ThreadId)
	if err != nil {
		return &org_forum_api.GetThreadResponse{
			Code:       org_forum_api.GetThreadResponse_CODE_NO_THREAD,
			ErrMsg:     "讨论会话不存在",
			ThreadInfo: emptyInfo,
		}, nil
	}

	userItemList, err := user_dao.UserInfoDao.ListById(ctx, []string{threadItem.UserId})
	if err != nil {
		return nil, err
	}
	thread := threadItem.ToForumThreadInfo()
	if len(userItemList) > 0 {
		thread.UserDisplayName = userItemList[0].BasicInfo.DisplayName
		thread.UserLogoUri = userItemList[0].BasicInfo.LogoUri
	}
	return &org_forum_api.GetThreadResponse{
		Code:       org_forum_api.GetThreadResponse_CODE_OK,
		ThreadInfo: thread,
	}, nil
}

func (apiImpl *OrgForumApiImpl) RemoveThread(ctx context.Context, req *org_forum_api.RemoveThreadRequest) (*org_forum_api.RemoveThreadResponse, error) {
	sessionItem, ok := dao.CacheDao.GetSession(ctx, req.SessionId)
	if !ok {
		return &org_forum_api.RemoveThreadResponse{
			Code:   org_forum_api.RemoveThreadResponse_CODE_WRONG_SESSION,
			ErrMsg: "会话不存在",
		}, nil
	}
	orgItem, err := org_dao.OrgInfoDao.Get(ctx, req.OrgId)
	if err != nil {
		return &org_forum_api.RemoveThreadResponse{
			Code:   org_forum_api.RemoveThreadResponse_CODE_NO_ORG,
			ErrMsg: "组织不存在",
		}, nil
	}
	if orgItem.OwnerUserId != sessionItem.UserId {
		exist, err := org_dao.MemberDao.Exist(ctx, req.OrgId, sessionItem.UserId)
		if err != nil {
			return nil, err
		}
		if !exist {
			return &org_forum_api.RemoveThreadResponse{
				Code:   org_forum_api.RemoveThreadResponse_CODE_NO_PERMISSION,
				ErrMsg: "没有权限",
			}, nil
		}
	}

	exist, err := org_dao.ForumDao.Exist(ctx, req.OrgId, req.ForumId)
	if err != nil {
		return nil, err
	}
	if !exist {
		return &org_forum_api.RemoveThreadResponse{
			Code:   org_forum_api.RemoveThreadResponse_CODE_NO_FORUM,
			ErrMsg: "讨论组不存在",
		}, nil
	}

	threadItem, err := org_dao.ForumThreadDao.Get(ctx, req.OrgId, req.ForumId, req.ThreadId)
	if err != nil { //记录不存在
		return &org_forum_api.RemoveThreadResponse{
			Code: org_forum_api.RemoveThreadResponse_CODE_OK,
		}, nil
	}
	if !(orgItem.OwnerUserId != sessionItem.UserId || threadItem.UserId == sessionItem.UserId) {
		return &org_forum_api.RemoveThreadResponse{
			Code:   org_forum_api.RemoveThreadResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	}

	dbSess, err := dao.StartSession()
	if err != nil {
		return nil, err
	}
	defer dao.EndSession(dbSess)

	ret, err := dbSess.WithTransaction(ctx, func(sessCtx mongo.SessionContext) (interface{}, error) {
		err = org_dao.ThreadContentDao.RemoveByThread(sessCtx, req.OrgId, req.ForumId, req.ThreadId)
		if err != nil {
			return nil, err
		}
		err = org_dao.ForumThreadDao.Remove(sessCtx, req.OrgId, req.ForumId, req.ThreadId)
		if err != nil {
			return nil, err
		}
		//更新论坛计数器
		count, err := org_dao.ForumThreadDao.Count(sessCtx, req.OrgId, req.ForumId)
		if err != nil {
			return nil, err
		}
		err = org_dao.ForumDao.UpdateThreadCount(sessCtx, req.OrgId, req.ForumId, count)
		if err != nil {
			return nil, err
		}
		return &org_forum_api.RemoveThreadResponse{
			Code: org_forum_api.RemoveThreadResponse_CODE_OK,
		}, nil
	})
	if err != nil {
		return nil, err
	}
	return ret.(*org_forum_api.RemoveThreadResponse), nil
}
